const { exec } = require('child_process');
var express = require('express');
var router = express.Router();
const {getFileText} = require('../utils/utils')
var fs = require('fs');
var path = require('path');
const DRIVE_LETTER = 'D:\\'
/**
 * 如果后文件后缀名在此列表中，则以文件返回
 */
const IMAGETYPES = {
  jpg:true,
  jpeg:true,
  svg:true,
  gif:true,
  pdf:true,
  png:true
}
/* GET home page. */
router.get('/*', function (req, res, next) {
  var openPath = path.join(DRIVE_LETTER,decodeURI(req.path));
  var sta = fs.lstatSync(openPath);
  // 访问目录
  if(sta.isDirectory()){
    res.render('index', { 
      title: '娄金亮的E盘',
      pathList:getJSONPath(openPath,req.path)
    });
  }
  // 访问文件
  else if(sta.isFile()){
    // 返回文件
    let suffix = getFileSuffix(openPath);
    if(suffix.toLocaleLowerCase() in IMAGETYPES){
      if(suffix.toLocaleLowerCase() == 'pdf'){
        res.set('content-type','application/pdf');
      }
      else{
        res.set('content-type','image/'+suffix);
      }
      res.sendFile(openPath);
    }
    // 显示代码
    else{
      res.render('index', { 
        title: '娄金亮的E盘',
        file:getFileText(openPath,suffix)
      });
    }
  }
});

// 执行命令
router.post('/*',function(req,res,next){
  // vscode打开
  if(req.body.command == 'code'){
    exec(`code ${path.join(DRIVE_LETTER,decodeURI(req.path))}`, (error, stdout, stderr) => {});
  }
  // 资源管理器中打开
  else if(req.body.command == 'open'){
    exec(`explorer ${path.join(DRIVE_LETTER,decodeURI(req.path))}`, (error, stdout, stderr) => {});
  }
  res.send({message:'ok'});
})

module.exports = router;



// 获取文件列表
function getJSONPath(openPath,reqPath){
  const files = fs.readdirSync(openPath,{withFileTypes:true});

  let jsonPath = [];
  files.forEach((item,index) =>{
    try {
      var visitPath = typeof item == 'string' ? item : item.name; //访问目录或文件8.9.3的时候还是一个字符串，切到10.13.0 item就是一个对象了。故做此判断
      var sta = fs.lstatSync(path.join(openPath,visitPath));
    } catch (error) {
      console.error(item,error);
    }

    if(sta){
      let obj = Object.create(null);
      obj.name = visitPath;
      obj.path = path.join(reqPath,obj.name).replace(/\\/g,'\/');
      if(sta.isDirectory()){
        obj.type = '目录';
        obj.children = fs.readdirSync(path.join(openPath,visitPath),{withFileTypes:true})
      }
      else{
        obj.type = '文件';
      }
      jsonPath.push(obj);
    }
  })
  return jsonPath;
}



function getFileSuffix(openPath){
  // 文件名字
  let basename = path.basename(openPath);
  // 文件后缀
  let suffix = path.extname(basename);
  
  // console.log(suffix,'-------------')
  // 如果没有获取到后缀名
  if(!suffix){
    if(basename){
      if(basename.charAt(0) == '.'){
        suffix = basename.slice(1);
      }
      else{
        suffix = basename;
      }
    }
  }
  else{
    // 将后缀前的 . 去掉
    suffix = suffix.slice(1);
  }
  return suffix;
}



